// 渲染函数
const goodslist = document.querySelector('.list')
const getstudentlist = async function () {
  const res = await axios({ url: '/students' })

  const { data } = res

  const goods = data
    .map((item, i) => {
      return ` <tr>
    <td>${item.name}</td>
    <td>${item.age}</td>
    <td>${item.gender ? '男' : '女'}</td>
    <td>第${item.group}组</td>
    <td>${item.hope_salary}</td>
    <td>${item.salary}</td>
    <td>${item.province + item.city + item.area}</td>
    <td>
      <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"data-id="${item.id}"></i></a>
      <a href="javascript:;" class="text-danger"><i class="bi bi-trash"data-id="${item.id}"></i></a>
    </td>
  </tr>`
    })
    .join('')
  document.querySelector('.total').innerHTML = res.data.length
  goodslist.innerHTML = goods
}
getstudentlist()

// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const ps = document.querySelector('[name=province]')
const cs = document.querySelector('[name=city]')
const as = document.querySelector('[name=area]')
const form = document.querySelector('#form')
const submitBtn = document.querySelector('#submit')
// 渲染省份
const initprovinces = async function () {
  const res = await axios({ url: '/api/province' })
  console.log(res)
  const provincehtml = res.data
    .map(item => {
      return `<option value="${item}">--${item}--</option>`
    })
    .join('')
  ps.innerHTML = `<option value="">--省份--</option>${provincehtml}`

  // 渲染城市
  ps.addEventListener('change', async function () {
    cs.innerHTML = ` <option value="">--城市--</option>`
    as.innerHTML = ` <option value="">--地区--</option>`
    const res = await axios({ url: '/api/city', params: { pname: ps.value } })

    const { data } = res
    const cityhtml = data
      .map(item => {
        return `  <option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = `<option value="">--城市--</option>${cityhtml}`
  })
  // 渲染市区
  cs.addEventListener('change', async function () {
    as.innerHTML = ` <option value="">--地区--</option>`
    if (!cs.value) return

    const res = await axios({ url: '/api/area', params: { pname: ps.value, cname: cs.value } })
    // console.log(res)
    const { data } = res
    const areahtml = data
      ?.map(item => {
        return `  <option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = `<option value="">--地区--</option>${areahtml}`
  })
}
initprovinces()
// 添加功能
const addBtn = document.querySelector('#openModal')
addBtn.addEventListener('click', function () {
  form.reset()
  modalBox.dataset.id = 'add'
  document.querySelector('.modal-title').innerHTML = '添加学员信息'
  modal.show()
})
// 给提交按钮绑定点击事件
submitBtn.addEventListener('click', async function () {
  const data = serialize(form, { hash: true })
  data.age = +data.age
  data.gender = +data.gender
  data.hope_salary = +data.hope_salary
  data.salary = +data.salary
  data.group = +data.group
  if (data.group < 1 || data.group > 8) return alert('请输入1-8的组号')
  modalBox.querySelector('#cb01').checked ? (data.gender = 1) : (data.gender = 0)
  for (const key in data) {
    if (!data[key]) return alert('输入的内容不能为空')
  }

  if (modalBox.dataset.id === 'add') {
    try {
      // 添加学生
      const res = await axios({ url: '/students', method: 'post', data })

      modal.hide()
      getstudentlist()
      alert(res.message)
    } catch (error) {
      alert(error)
    }
  } else {
    // 修改学生
    try {
      const res = await axios({ url: '/students/' + modalBox.dataset.id, method: 'put', data })
      modal.hide()
      getstudentlist()
      alert(res.message)
    } catch (error) {
      alert(error)
    }
  }
})

goodslist.addEventListener('click', async function (e) {
  if (e.target.classList.contains('bi-pen')) {
    const id = e.target.dataset.id
    const res = await axios({ url: '/students/' + id })
    console.log(res)
    const nodelist = modalBox.querySelectorAll('[name]')
    nodelist.forEach(item => {
      if (item.name === 'gender')
        res.data[item.name]
          ? (modalBox.querySelector('#cb01').checked = true)
          : (modalBox.querySelector('#cb02').checked = true)

      item.value = res.data[item.name]
    })

    const { data: cityData } = await axios({ url: '/api/city', params: { pname: res.data.province } })
    const cityhtml = cityData
      .map(item => {
        return `  <option value="${item}">--${item}--</option>`
      })
      .join('')
    console.log(cityData)
    cs.innerHTML = `<option value="">--城市--</option>${cityhtml}`
    cs.value = res.data.city
    const { data: areadata } = await axios({
      url: '/api/area',
      params: { pname: res.data.province, cname: res.data.city }
    })
    console.log(res)
    const areahtml = areadata
      ?.map(item => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = `<option value="">--地区--</option>${areahtml}`
    as.value = res.data.area

    modalBox.dataset.id = id
    document.querySelector('.modal-title').innerHTML = '修改学员信息'
    modal.show()
  }
  if (e.target.classList.contains('bi-trash')) {
    const id = e.target.dataset.id
    axios({ url: '/students/' + id, method: 'DELETE' })
    getstudentlist()
    alert('删除成功')
  }
})
